package com.gitee.connect_screen;

import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowMetrics;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.fragment.app.Fragment;

import com.gitee.connect_screen.job.DisplaylinkMonitor;
import com.gitee.connect_screen.job.VirtualDisplayArgs;
import com.gitee.connect_screen.job.ProjectViaDisplaylink;
import com.gitee.connect_screen.shizuku.ShizukuUtils;

import java.util.Arrays;

public class DisplaylinkFragment extends Fragment {
    private static final String ARG_DEVICE = "device";
    private UsbDevice device;
    private DisplaylinkState displaylinkState;
    private View sourceScreenSizeLayout;
    private View aspectRatioExplanation;
    private CheckBox rotatesWithContentCheckbox;
    private CheckBox skipMediaProjectionPermissionCheckbox;
    private CheckBox autoOpenLastAppCheckbox;
    private View frameRateLayout;
    private View launchAppButton;
    private EditText dpiInput;

    public static DisplaylinkFragment newInstance() {
        DisplaylinkFragment fragment = new DisplaylinkFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DisplaylinkPref.load(getContext());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        UsbManager usbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
        for (UsbDevice usbDevice : usbManager.getDeviceList().values()) {
            DisplaylinkMonitor.handleDisplaylink(usbDevice);
        }
        device = usbManager.getDeviceList().get(State.displaylinkDeviceName);
        if (device == null) {
            TextView textView = new TextView(getActivity());
            textView.setText("未找到 Displaylink 设备。USB 2.0 的手机需要插入 Displaylink 扩展坞才能接显示器。");
            return textView;
        }
        displaylinkState = State.displaylinkState;
        displaylinkState.device = device;
        View view = inflater.inflate(R.layout.fragment_displaylink, container, false);
        rotatesWithContentCheckbox = view.findViewById(R.id.rotatesWithContentCheckbox);
        skipMediaProjectionPermissionCheckbox = view.findViewById(R.id.skipMediaProjectionPermissionCheckbox);
        autoOpenLastAppCheckbox = view.findViewById(R.id.autoOpenLastAppCheckbox);
        launchAppButton = view.findViewById(R.id.launch_app_button);

        TextView detailContent = view.findViewById(R.id.detailContent);
        Button mirrorViaDisplaylinkButton = view.findViewById(R.id.mirrorViaDisplaylinkButton);
        EditText monitorWidthInput = view.findViewById(R.id.displayWidthInput);
        EditText monitorHeightInput = view.findViewById(R.id.monitorHeightInput);

        sourceScreenSizeLayout = view.findViewById(R.id.sourceScreenSizeLayout);
        EditText sourceWidthInput = view.findViewById(R.id.sourceWidthInput);
        EditText sourceHeightInput = view.findViewById(R.id.sourceHeightInput);
        aspectRatioExplanation = view.findViewById(R.id.aspectRatioExplanation);
        frameRateLayout = view.findViewById(R.id.frameRateLayout);

        Spinner projectionModeSpinner = view.findViewById(R.id.projectionModeSpinner);

        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(
            getContext(),
            android.R.layout.simple_spinner_item,
            Arrays.stream(ProjectionMode.values())
                  .map(mode -> {
                      switch(mode) {
                          case MIRROR: return "普通镜像";
                          case MIRROR_AND_CROP_16_9: return "16:9裁剪";
                          case SINGLE_APP: return "投屏单个应用（需要 shizuku 授权）";
                          default: return mode.name();
                      }
                  })
                  .toArray(String[]::new)
        );
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        projectionModeSpinner.setAdapter(spinnerAdapter);
        
        if (DisplaylinkPref.projectionMode != null) {
            projectionModeSpinner.setSelection(DisplaylinkPref.projectionMode.ordinal());
        }


        projectionModeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                DisplaylinkPref.projectionMode = ProjectionMode.values()[position];
                updateView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Do nothing
            }
        });

        // 获取主屏幕尺寸
        WindowManager windowManager = (WindowManager) requireActivity().getSystemService(Context.WINDOW_SERVICE);
        int pxWidth = 0, pxHeight = 0;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
            WindowMetrics windowMetrics = windowManager.getMaximumWindowMetrics();
            pxWidth = windowMetrics.getBounds().width();
            pxHeight = windowMetrics.getBounds().height();
        } else {
            Display display = windowManager.getDefaultDisplay();
            DisplayMetrics metrics = new DisplayMetrics();
            display.getRealMetrics(metrics);
            pxWidth = metrics.widthPixels;
            pxHeight = metrics.heightPixels;
        }

        if (DisplaylinkPref.sourceWidth != 0) {
            sourceWidthInput.setText(String.valueOf(DisplaylinkPref.sourceWidth));
        } else {
            sourceWidthInput.setText(String.valueOf(pxWidth));
        }
        if (DisplaylinkPref.sourceHeight != 0) {
            sourceHeightInput.setText(String.valueOf(DisplaylinkPref.sourceHeight));
        } else {
            sourceHeightInput.setText(String.valueOf(pxHeight));
        }

        // 监听输入框变化并更新 usbState
        TextWatcher dimensionsWatcher = new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                try {
                    DisplaylinkPref.sourceWidth = Integer.parseInt(sourceWidthInput.getText().toString());
                    DisplaylinkPref.sourceHeight = Integer.parseInt(sourceHeightInput.getText().toString());
                    DisplaylinkPref.monitorWidth = Integer.parseInt(monitorWidthInput.getText().toString());
                    DisplaylinkPref.monitorHeight = Integer.parseInt(monitorHeightInput.getText().toString());
                    updateView();
                } catch (NumberFormatException e) {
                    // 忽略无效输入
                }
            }
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {}
        };
        
        sourceWidthInput.addTextChangedListener(dimensionsWatcher);
        sourceHeightInput.addTextChangedListener(dimensionsWatcher);
        monitorWidthInput.addTextChangedListener(dimensionsWatcher);
        monitorHeightInput.addTextChangedListener(dimensionsWatcher);

        // 添加分辨率预设选项
        Spinner resolutionPresetSpinner = view.findViewById(R.id.resolutionPresetSpinner);
        String[] resolutionPresets = new String[]{"快捷设置", "1080p", "1440p", "2160p", "ipad4"};
        ArrayAdapter<String> resolutionAdapter = new ArrayAdapter<>(
            getContext(),
            android.R.layout.simple_spinner_item,
            resolutionPresets
        );
        resolutionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        resolutionPresetSpinner.setAdapter(resolutionAdapter);
        
        resolutionPresetSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 1: // 1080p
                        monitorWidthInput.setText("1920");
                        monitorHeightInput.setText("1080");
                        break;
                    case 2: // 1440p
                        monitorWidthInput.setText("2560");
                        monitorHeightInput.setText("1440");
                        break;
                    case 3: // 2160p
                        monitorWidthInput.setText("3840");
                        monitorHeightInput.setText("2160");
                        break;
                    case 4: // ipad4
                        monitorWidthInput.setText("2048");
                        monitorHeightInput.setText("1536");
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Do nothing
            }
        });

        StringBuilder sb = new StringBuilder();
        sb.append("设备名称: ").append(device.getDeviceName()).append("\n");
        sb.append("制造商: ").append(device.getManufacturerName() != null ? device.getManufacturerName() : "未知").append("\n");
        sb.append("产品名称: ").append(device.getProductName() != null ? device.getProductName() : "未知").append("\n");
        sb.append("厂商ID: ").append(device.getVendorId()).append("\n");
        sb.append("产品ID: ").append(device.getProductId()).append("\n");
        sb.append("设备类: ").append(device.getDeviceClass()).append("\n");
        sb.append("设备子类: ").append(device.getDeviceSubclass()).append("\n");
        sb.append("协议: ").append(device.getDeviceProtocol()).append("\n");

        sb.append("Native Driver: ").append(displaylinkState.nativeDriver != null ? "已连接" : "未连接").append("\n");
        if (DisplaylinkPref.monitorWidth != 0) {
            monitorWidthInput.setText(String.valueOf(DisplaylinkPref.monitorWidth));
        } else if (displaylinkState.monitorInfo != null) {
            monitorWidthInput.setText(String.valueOf(displaylinkState.monitorInfo.a[0].width));
        } else {
            monitorWidthInput.setText("未连接");
        }
        if (DisplaylinkPref.monitorHeight != 0) {
            monitorHeightInput.setText(String.valueOf(DisplaylinkPref.monitorHeight));
        } else if (displaylinkState.monitorInfo != null) {
            monitorHeightInput.setText(String.valueOf(displaylinkState.monitorInfo.a[0].height));
        } else {
            monitorHeightInput.setText("未连接");
        }
        if (displaylinkState.getVirtualDisplay() != null) {
            Display display = displaylinkState.getVirtualDisplay().getDisplay();
            DisplayMetrics metrics = new DisplayMetrics();
            display.getRealMetrics(metrics);
            sb.append("虚拟显示器: ").append(display.getDisplayId()).append(", 宽: ").append(metrics.widthPixels).append(", 高: ").append(metrics.heightPixels).append("\n");
        } else {
            sb.append("虚拟显示器: ").append("未连接").append("\n");
        }
        sb.append("总发送帧数: ").append(displaylinkState.frameCounter).append("\n");
        sb.append("最近发送帧状态码: ").append(Arrays.toString(displaylinkState.recentPostFrameResultCodes)).append("\n");

        detailContent.setText(sb.toString());

        mirrorViaDisplaylinkButton.setOnClickListener(v -> {
            DisplaylinkPref.save(getContext());
            State.startNewJob(new ProjectViaDisplaylink(device, displaylinkState.virtualDisplayArgs));
        });

        rotatesWithContentCheckbox.setChecked(DisplaylinkPref.rotatesWithContent);
        rotatesWithContentCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            DisplaylinkPref.rotatesWithContent = isChecked;
        });

        skipMediaProjectionPermissionCheckbox.setChecked(DisplaylinkPref.skipMediaProjectionPermission);
        skipMediaProjectionPermissionCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            DisplaylinkPref.skipMediaProjectionPermission = isChecked;
        });

        autoOpenLastAppCheckbox.setChecked(DisplaylinkPref.autoOpenLastApp);
        autoOpenLastAppCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            DisplaylinkPref.autoOpenLastApp = isChecked;
        });

        EditText frameRateInput = view.findViewById(R.id.frameRateInput);
        frameRateInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                try {
                    int frameRate = Integer.parseInt(s.toString());
                    DisplaylinkPref.refreshRate = frameRate;
                    updateView();
                } catch (NumberFormatException e) {
                    // 忽略无效输入
                }
            }
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {}
        });
        
        // 如果 usbState 中已有帧率值，则显示在输入框中
        if (DisplaylinkPref.refreshRate > 0) {
            frameRateInput.setText(String.valueOf(DisplaylinkPref.refreshRate));
        }

        // 添加查看虚拟显示器按钮
        Button viewVirtualDisplayButton = view.findViewById(R.id.view_virtual_display_button);
        if (displaylinkState.getVirtualDisplay() != null) {
            viewVirtualDisplayButton.setVisibility(View.VISIBLE);
            viewVirtualDisplayButton.setOnClickListener(v -> {
                State.breadcrumbManager.pushBreadcrumb("虚拟显示器", () ->
                    DisplayDetailFragment.newInstance(displaylinkState.getVirtualDisplay().getDisplay().getDisplayId())
                );
            });
            launchAppButton.setOnClickListener(v -> {
                Context context = State.currentActivity.get();
                Intent intent = new Intent(context, LauncherActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(LauncherActivity.EXTRA_TARGET_DISPLAY_ID, displaylinkState.getVirtualDisplay().getDisplay().getDisplayId());
                context.startActivity(intent);
            });
        } else {
            viewVirtualDisplayButton.setVisibility(View.GONE);
        }

        dpiInput = view.findViewById(R.id.dpiInput);
        dpiInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                try {
                    int dpi = Integer.parseInt(s.toString());
                    DisplaylinkPref.dpi = dpi;
                    updateView();
                } catch (NumberFormatException e) {
                    // 忽略无效输入
                }
            }
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {}
        });
        
        // 如果已有DPI值，则显示在输入框中
        if (DisplaylinkPref.dpi > 0) {
            dpiInput.setText(String.valueOf(DisplaylinkPref.dpi));
        }

        updateView();

        return view;
    }

    private void updateView() {
        if (displaylinkState == null) return;
        
        // 更新16:9模式相关视图
        boolean is16_9Mode = DisplaylinkPref.projectionMode == ProjectionMode.MIRROR_AND_CROP_16_9;
        sourceScreenSizeLayout.setVisibility(is16_9Mode ? View.VISIBLE : View.GONE);
        
        // 更新单应用模式相关视图
        boolean isSingleAppMode = DisplaylinkPref.projectionMode == ProjectionMode.SINGLE_APP;
        rotatesWithContentCheckbox.setVisibility(isSingleAppMode ? View.VISIBLE : View.GONE);
        skipMediaProjectionPermissionCheckbox.setVisibility(isSingleAppMode ? View.VISIBLE : View.GONE);
        autoOpenLastAppCheckbox.setVisibility(isSingleAppMode ? View.VISIBLE : View.GONE);
        launchAppButton.setVisibility(isSingleAppMode ? View.VISIBLE : View.GONE);
        if (displaylinkState.getVirtualDisplay() == null) {
            launchAppButton.setVisibility(View.GONE);
        }

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.UPSIDE_DOWN_CAKE && ShizukuUtils.hasShizukuStarted()) {
            frameRateLayout.setVisibility(View.VISIBLE);
        }

            // 如果在16:9模式下，更新裁剪说明
        if (is16_9Mode) {
            try {
                int sourceWidth = DisplaylinkPref.sourceWidth;
                int sourceHeight = DisplaylinkPref.sourceHeight;
                int monitorWidth = DisplaylinkPref.monitorWidth;
                int monitorHeight = DisplaylinkPref.monitorHeight;
                int maxSourceDim = Math.max(sourceWidth, sourceHeight);
                int minSourceDim = Math.min(sourceWidth, sourceHeight);
                if (minSourceDim == 0) {
                    throw new NumberFormatException();
                }
                int virtualDisplayWidth = monitorHeight * maxSourceDim / minSourceDim;

                StringBuilder explanation = new StringBuilder();
                explanation.append("16:9裁剪计算过程：\n");
                explanation.append("1. 主屏尺寸：").append(sourceWidth).append("x").append(sourceHeight).append("\n");
                explanation.append("2. 显示器尺寸：").append(monitorWidth).append("x").append(monitorHeight).append("\n");
                explanation.append("3. 虚拟屏的高度固定为显示器的高度：").append(monitorHeight).append("\n");
                explanation.append("4. 根据高度计算虚拟屏的宽度：").append(virtualDisplayWidth).append("\n");
                explanation.append("5. 左右会裁切的画面宽度：").append((virtualDisplayWidth - monitorWidth) / 2).append("\n");

                displaylinkState.virtualDisplayArgs = new VirtualDisplayArgs(
                    "DisplayLink", 
                    DisplaylinkPref.monitorWidth, 
                    DisplaylinkPref.monitorHeight,
                    is16_9Mode ? virtualDisplayWidth : DisplaylinkPref.monitorWidth,
                    DisplaylinkPref.refreshRate,
                    DisplaylinkPref.dpi,
                    DisplaylinkPref.rotatesWithContent
                );
                ((TextView) aspectRatioExplanation).setText(explanation.toString());
            } catch (NumberFormatException e) {
                // 忽略无效输入
            }
        } else {
            displaylinkState.virtualDisplayArgs = new VirtualDisplayArgs(
                "DisplayLink", 
                DisplaylinkPref.monitorWidth, 
                DisplaylinkPref.monitorHeight, 
                DisplaylinkPref.monitorWidth, 
                DisplaylinkPref.refreshRate,
                DisplaylinkPref.dpi,
                DisplaylinkPref.rotatesWithContent
            );
        }
        aspectRatioExplanation.setVisibility(is16_9Mode ? View.VISIBLE : View.GONE);
    }

}